package com.example.rushbuy.consumer;

import com.example.rushbuy.LockObjHolder;
import com.example.rushbuy.event.BuyEvent;
import com.example.rushbuy.event.CheckTimeoutOrderEvent;
import com.example.rushbuy.mapper.OrderMapper;
import com.example.rushbuy.mapper.RushItemMapper;
import com.example.rushbuy.po.Order;
import com.example.rushbuy.po.RushItem;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

@Service
@RocketMQMessageListener(topic = "rushbuy-delay", consumerGroup = "rushbuy-consumer-2")
public class DelayMqConsumer implements RocketMQListener<CheckTimeoutOrderEvent> {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RushItemMapper rushItemMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
    public void onMessage(CheckTimeoutOrderEvent checkTimeoutOrderEvent) {
        System.out.println(checkTimeoutOrderEvent.getOrder());
        Order eventOrder = checkTimeoutOrderEvent.getOrder();
        //检查是否支付订单了，没支付，设置为超时，且恢复库存
        Order order = orderMapper.selectByPrimaryKey(eventOrder.getId());
        if (order.getPayState() != 1) {
            order.setIsTimeout(true);
            orderMapper.updateByPrimaryKey(order);
            //通过itemid更新库存信息
//            synchronized (LockObjHolder.lock){
            RushItem rushItem = rushItemMapper.selectByPrimaryKeyLock(order.getItemId());
            rushItem.setStore(rushItem.getStore() + order.getBuyCount());
            //此处高并发下会有问题，需要加一个分布式锁
            rushItemMapper.updateByPrimaryKey(rushItem);
            redisTemplate.opsForValue().increment("store:" + rushItem.getId(), order.getBuyCount());
//            }
            System.out.println("订单超时，回滚库存,订单ID："+order.getId());
        }
    }
}
